package com.ken.apigateway.lancher;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ken.apigateway.utils.HeaderUtil;
import com.netflix.zuul.context.RequestContext;
import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 从请求头中取出指定的lancher
 */
public class RequestHeaderServiceLancherHandler extends ServiceLancherHandler {
    public static final String RIBBON_LANCHER_MAP = "ribbon-lancher-map";

    @Override
    String getServiceLancher(String serviceId) {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String lancherMapStr = HeaderUtil.getHeader(request, RIBBON_LANCHER_MAP);
        if (StringUtils.isEmpty(lancherMapStr)){
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(lancherMapStr);
        if (Objects.isNull(jsonObject)){
            return null;
        }
        String serviceLancher = jsonObject.getString(serviceId);
        if (StringUtils.isEmpty(serviceLancher)){
            return null;
        }
        return serviceLancher;
    }
}
